package com.wzy.server.config;

//权限控制
//根据请求url分析请求所需要的角色


import com.wzy.server.pojo.Menu;
import com.wzy.server.pojo.Role;
import com.wzy.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IMenuService menuService;//根据角色查询菜单列表

    AntPathMatcher antPathMatcher= new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
//        获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
//        获取menus
        List<Menu> menus= menuService.getMenusWithRole();
//        循环判断menus
        for (Menu menu : menus){
//            判断请求url与菜单角色是否匹配
            if (antPathMatcher.match(menu.getUrl(),requestUrl)){
//                获取角色字符
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
//                匹配上的角色放入list中
                return SecurityConfig.createList(str);
            }
        }
//        没匹配的url默认登陆即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
